angular.module("driver").controller("OnesdataCtrl", ['$scope', '$meteor',
  '$rootScope', '$state', '$ionicPopup', 'Map', '$ionicActionSheet',
  '$timeout', 'Upload', 'IMGSERVER', '$ionicLoading', 'FileUploader', '$cordovaImagePicker', '$cordovaFileTransfer',
  function($scope, $meteor, $rootScope, $state, $ionicPopup, Map,
    $ionicActionSheet, $timeout, Upload, IMGSERVER, $ionicLoading, FileUploader, $cordovaImagePicker, $cordovaFileTransfer) {


    //$scope.user = Meteor.user();
    $meteor.subscribe('userData').then(function(subscriptionHandle) {
      $scope.user = $meteor.object(Meteor.users, Meteor.userId());
    });

    // Triggered on a button click, or some other target
    $scope.changpic = function() {

      // Show the action sheet
      var hideSheet = $ionicActionSheet.show({
        buttons: [{
          text: '拍照'
        }, {
          text: '相册'
        }],
        destructiveText: '删除',
        titleText: '选取图片',
        cancelText: '取消',
        cancel: function() {
          // add cancel code..
        },
        buttonClicked: function(index) {
          return true;
        }
      });

    };


    $scope.saveinf = function() {

      var confirmPopup = $ionicPopup.confirm({
        title: '即将保存！',
        cancelText: '取消',
        cancelType: 'button-royal button-outline',
        okText: '确定',
        okType: 'button-assertive button-outline',
      });
      confirmPopup.then(function(res) {
        if (res) {
          $scope.user.save().then(function() {
            $state.go('more');
          }, function(error) {
            console.log(error);
          });
          //$state.go('more');
          //console.log('取消订单');
        } else {
          console.log('尚未保存');
        }
      });


    };


    var uploadfiles = null;
    $scope.imgSrc = null;
    $scope.addImages = function(files, file, event) {
      if (files.length > 0)
        $scope.selectedImage = files[0];
    };

    $scope.show = function() {
      $ionicLoading.show({
        template: '<ion-spinner></ion-spinner>\
        <a>头像上传中...</a>'
      });
    };
    $scope.hide = function() {
      $ionicLoading.hide();
    };

    $scope.upload = function() {
      var item = $scope.uploader.queue[0];
      //console.log(item);
      //Resizer.resize(item._file, {width: 200, height: 200, cropSquare: false}, function(err, file) {
      //if (err) alert('err');

      //item._file = file;
      item.upload();
      $scope.show();
      //});
      /*
      var file = $scope.selectedImage;
      Resizer.resize(file, {
        width: 200,
        height: 200,
        cropSquare: false
      }, function(err, file) {
        $scope.show();
        Upload.upload({
          url: IMGSERVER.uploadurl,
          method: 'POST',
          //fileName: $scope.user.username + type,
          file: file
        }).progress(function(evt) {
          console.log(evt);
        }).success(function(data, status, headers, config) {
          var path = data;
          //console.log(path);
          $meteor.call('uploadImage', 'face', IMGSERVER.showurl + path);
          $scope.hide();
          $scope.selectedImage = undefined;
        });
      });
*/
    };


    $scope.imagePicker = function() {
      var options = {
        maximumImagesCount: 1,
        quality: 80
      };
      $cordovaImagePicker.getPictures(options)
        .then(function(results) {
          if (results.length) {
            fileURL = results[0];
            $scope.show();
            $cordovaFileTransfer.upload(IMGSERVER.uploadurl, fileURL, {})
              .then(function(result) {
                //alert(JSON.stringify(result));
                $scope.hide();
                console.log(results);
                $meteor.call('uploadImage', 'face', IMGSERVER.showurl + result.response);
              }, function(err) {
                $scope.hide();
              }, function(progress) {
                //alert('progress')
              });
          }
        }, function(error) {
          alert('发生错误，请重试');
          // error getting photos
        });
    };

    $scope.cancel = function() {
      $scope.selectedImage = undefined;
      $scope.uploader.queue.pop();
    };

    $scope.isDriver = function() {
      //console.log(this.userId)
      if (!Meteor.user()) return false;

      return Roles.userIsInRole(Meteor.user()._id, 'driver');
    };

    $scope.uploader = new FileUploader();
    var uploader = $scope.uploader = new FileUploader({
      url: IMGSERVER.uploadurl
    });

    // FILTERS

    uploader.filters.push({
      name: 'imageFilter',
      fn: function(item /*{File|FileLikeObject}*/ , options) {
        var type = '|' + item.type.slice(item.type.lastIndexOf('/') + 1) + '|';
        return '|jpg|png|jpeg|bmp|gif|'.indexOf(type) !== -1;
      }
    });

    // CALLBACKS

    uploader.onWhenAddingFileFailed = function(item /*{File|FileLikeObject}*/ , filter, options) {
      console.info('onWhenAddingFileFailed', item, filter, options);
    };
    uploader.onAfterAddingFile = function(fileItem) {
      console.info('onAfterAddingFile', fileItem);
    };
    uploader.onAfterAddingAll = function(addedFileItems) {
      $scope.selectedImage = true;
      if (uploader.queue.length > 1)
        uploader.queue.shift();
      console.info('onAfterAddingAll', addedFileItems);

      $scope.upload();
    };
    uploader.onBeforeUploadItem = function(item) {
      console.info('onBeforeUploadItem', item);
    };
    uploader.onProgressItem = function(fileItem, progress) {
      console.info('onProgressItem', fileItem, progress);
    };
    uploader.onProgressAll = function(progress) {
      console.info('onProgressAll', progress);
    };
    uploader.onSuccessItem = function(fileItem, response, status, headers) {
      console.info('onSuccessItem', fileItem, response, status, headers);
    };
    uploader.onErrorItem = function(fileItem, response, status, headers) {
      console.info('onErrorItem', fileItem, response, status, headers);
    };
    uploader.onCancelItem = function(fileItem, response, status, headers) {
      console.info('onCancelItem', fileItem, response, status, headers);
    };
    uploader.onCompleteItem = function(fileItem, response, status, headers) {
      $meteor.call('uploadImage', 'face', IMGSERVER.showurl + response);
      console.info('onCompleteItem', fileItem, response, status, headers);
      $scope.selectedImage = false;
      $scope.uploader.queue.pop();
      $scope.hide();
    };
    uploader.onCompleteAll = function() {
      console.info('onCompleteAll');
    };

    console.info('uploader', uploader);

  }
]);